/**
 * @author Federico Consoli
 *
 * Released under GNU GPLv3 (http://www.gnu.org/licenses/gpl-3.0.txt)
 */

//Max lenght directory
#define MAXPATHLEN 300
#define cs(x) Connection::char_to_string(x)
#define cus(x) Connection::char_to_uns_short(x)

#include "libreria.h"
#include "client_fun.h"


string ip="127.0.0.1";
string port="40000";
        


/** Structure that contains parameters to pass to each thread */
struct Thread_param {
    /** Name of the client (CLIENT0, CLIENT1...) */
    string name;
    /** Pwd of each client*/
    string directory;
    
};

/** Thread function */
void *go_client(void*args) {
    Thread_param*elem = (Thread_param*) args;
    string comando = "./client ";
    comando += elem->name + " 1 ";
    comando += ip + " ";
    comando += port;
    chdir(elem->directory.c_str());
    /** Start every client as a process*/
    system(comando.c_str());
    //delete elem;
    return NULL;
}

int main(int argc, const char * argv[]) {
    if ((argc ==2 && argv[1][1]=='h')) {
        cout << "\nSintax: ./client_test <ip_reg> <port_reg> \n\n";
        cout << "Parameters are preparatory in order of entry, so you can entry no value\n";
        cout << "Or you can entry only ip_reg or only ip_reg+port_reg etc. etc.\n\n";
        cout << "ip_reg default: 127.0.0.1\n";
        cout << "port_reg default: 40000\n\n";
        return 0;
    }
    
    switch (argc) {
        case 2:
            ip=cs(argv[1]);
            break;
        case 3:
            ip=cs(argv[1]);
            port=cs(argv[2]);            
            break;
    }
    
    pthread_t t1[5];
    char path[MAXPATHLEN];
    getcwd(path, MAXPATHLEN);
    string dire;
    if (strlen(path))
        dire = path;
    struct stat st;
    Thread_param *elem_array[5];
    for (int i = 0; i < 5; i++) {
        ostringstream out;
        out << i;
        string temp_dir = dire;
        temp_dir += "/client" + out.str();
        /** Check if every client's directory exist */
        if (stat(temp_dir.c_str(), &st) == 0)
            cout << temp_dir + " exist \n";
        else {
            cout << temp_dir + " does not exist! Do you read README? \n";
            return 0;
        }
        Thread_param *elem = new Thread_param;
        elem_array[i]=elem;
        /** Build client name */
        elem->name = "CLIENT_" + out.str();
        elem->directory = temp_dir;
        pthread_create(&t1[i], NULL, &go_client, (void*) elem);
    }
    for (int i = 0; i < 5; i++) {
        pthread_join(t1[i], NULL);
        delete elem_array[i];
    }
   // delete elem;
    cout << "END TEST\n";
    return 0;
}




